package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.dto.AppDTO;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.TransactionService;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class PayController {

    @Autowired
    TransactionService transactionService;
    @Reference
    AppService appService;



    /**
     *     支付入口  (扫码请求地址)
     *  例子:   http://127.0.0.1:56010/transaction/pay-entry/CVYFTGucvhgjVYGHcvy
     * @param ticket
     * @param request
     * @return
     */
    @RequestMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket, HttpServletRequest request) throws Exception {
        //解析ticket
        String param_json = EncryptUtil.decodeUTF8StringBase64(ticket);
        //转为对象
        PayOrderDTO payOrderDTO = JSON.parseObject(param_json, PayOrderDTO.class);
        // merchantId=xxx&appId=xxx&storeId=xxx
        String params = ParseURLPairUtil.parseURLPair(payOrderDTO);
        //判断客户端类型
        String userAgent = request.getHeader("User-Agent");

        BrowserType browserType = BrowserType.valueOfUserAgent(userAgent);
        switch (browserType){
            case ALIPAY:
                return "forward:/pay-page?"+params;
            case WECHAT:  //TODO
                return "forward:/pay-page?"+params;

        }

        return "pay_error";
    }

    @ApiOperation("支付宝门店下单付款")
    @PostMapping("/createAliPayOrder")
    public void createAlipayOrderForStore(OrderConfirmVO orderConfirmVO, HttpServletRequest request,HttpServletResponse response) throws Exception{

        PayOrderDTO payOrderDTO = PayOrderConvert.INSTANCE.vo2Dto(orderConfirmVO);
        //将金额元转为分
        String totalAmount = AmountUtil.changeY2F(String.valueOf(payOrderDTO.getTotalAmount()));
        payOrderDTO.setTotalAmount(Integer.parseInt(totalAmount));
        //客户端Ip
        payOrderDTO.setClientIp(IPUtil.getIpAddr(request));
        AppDTO appDTO = appService.getAppById(orderConfirmVO.getAppId());
        payOrderDTO.setMerchantId(appDTO.getMerchantId());
        //保存商户订单
        //调用支付渠道代理服务对接支付宝
        PaymentResponseDTO<String> responseDTO = transactionService.submitOrderByAli(payOrderDTO);

        //将表单写到浏览器
        String form = responseDTO.getContent();
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();

    }


}
